import type { Viewer } from 'cesium';
import * as Cesium from 'cesium'

/**
 * 因为Cesium中没有组的概念，所以自己给他封装一个组
 * @param { Cesium.Viewer } view 地球的图层
 */
export class useEarthGroup {
    viewer: Viewer | null = null;
    private entitys: Cesium.EntityCollection | null = null;
    constructor(view: Cesium.Viewer) {
        this.viewer = view;
        if (!this.viewer) return;

        this.entitys = new Cesium.EntityCollection(this.viewer.scene);
        return this;
    }
    /**
     * 更换图层，更换图层会将原来组内所有的实体全部删除
     * @param view 
     */
    setViewer(view: Cesium.Viewer) {
        this.viewer = view;
        this.removeAllEntitys()
    }
    /**
     * 获取当前的组对象
     * @returns Cesium.EntityCollection
     */
    getCurrentEntitys() {
        return this.entitys;
    }
    /**
     * 根据id获取组内的实体
     * @param id string
     * @returns Entity或null
     */
    getGroupById(id: string) {
        return this.entitys?.getById(id);
    }
    /**
     * 查看该id或是实体是否包含在组中
     * @param entity any | Cesium.Entity
     */
    groupIsContains(entity: any) {
        let e: Cesium.Entity | undefined;
        e = entity instanceof Cesium.Entity ? entity : (this.entitys?.getById(entity.toString()));
        return e && this.entitys?.contains(e)
    }
    /**
     * 添加实体
     * @param option object | Cesium.Entity
     * @returns 新创建的对象或传来的对象
     */
    addEntity(option: object | Cesium.Entity) {
        if (!this.viewer) return null;
        let result = option;
        if (!(option instanceof Cesium.Entity)) {
            // 往地图中添加元素时先检查地图中有没有相同id的元素，有的话将上一个删除
            // let _ent = this.viewer?.entities.getById(option.id);
            // _ent && this.viewer?.entities.remove(_ent)
            result = this.viewer.entities.add(option);
        }
        this.entitys?.add(option)
        return result;
    }
    /**
     * 根据id删除内容
     * @param entity 实体或实体id
     * @returns boolean
     */
    removeGroupEntityById(entity: string | Cesium.Entity) {
        if (entity instanceof Cesium.Entity) {
            this.entitys?.remove(entity);
            this.viewer?.entities.remove(entity);
            return true;
        } else {
            let e = this.entitys?.getById(entity);
            if (!e) return false;
            this.entitys?.remove(e);
            this.viewer?.entities.remove(e);
            return true;
        }
    }
    /**
     * 删除组内全部内容
     * @returns 无
     */
    removeAllEntitys() {
        if (!this.entitys || !this.viewer) return null;
        let e = this.entitys?._entities._array;
        for (let entity of e) {
            this.viewer.entities.remove(entity);
        }
        this.entitys.removeAll()
    }
}